package cn.z2huo.demo.kafka.apache.jackson;

import cn.z2huo.core.lang.SingletonHolder;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.text.SimpleDateFormat;

/**
 * <p>
 *
 * @author z2huo
 */
public final class KafkaJsonMapper {

    public static final JsonMapper INSTANCE = get();

    private KafkaJsonMapper(){
    }

    private static JsonMapper get() {
        return SingletonHolder.get(KafkaJsonMapper.class.getName(), () -> {
            JsonMapper.Builder builder = JsonMapper.builder();

            // 序列化配置
            builder
                    // 是否将 JSON 输出格式化为缩进格式
                    .disable(SerializationFeature.INDENT_OUTPUT)
                    // 是否将 Date 类型输出为时间戳
                    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    // 是否将枚举输出为名称
                    .disable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
//                    .disable(MapperFeature.USE_STATIC_TYPING)

            ;

            // 反序列化配置
            builder
                    // 反序列化时忽略 JSON 存在但 Java 类中不存在的属性
                    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                    // 是否允许 JSON 中的字段名不带引号
                    .disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
                    // 是否允许单引号
                    .disable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
                    // 是否允许注释
                    .disable(JsonParser.Feature.ALLOW_COMMENTS)
//                    .enable(StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION)
//                    .enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES)
            ;



            JsonMapper jsonMapper = builder.build();
            // 处理 jsr310 的时间
            jsonMapper.registerModule(new JavaTimeModule());
            jsonMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

            return jsonMapper;
        });
    }
}
